<?php
session_start();
	// TODO don't hardcode the reminder service
	// TODO use the session to key on user
	
	function generateUID($reminder_node) {
		return $reminder_node->id . $reminder_node->category . $reminder_node->reminder_date;
	}
	
	function printEvent($reminder_node) {
		printf("BEGIN:VEVENT\n");
		printf("UID:%s@scs.tufts.edu\n", generateUID($reminder_node));
		$dateparts = explode('-', $reminder_node->reminder_date);
		printf("DTSTART:%s%s%s\n", $dateparts[0], $dateparts[1], $dateparts[2]);
		printf("SUMMARY:%s\n", $reminder_node->last + ", " + $reminder_node->first + " (" $reminder_node->email) + ")";
		printf("END:VEVENT\n");
	}
	
	function printCancel($reminder_node) {
		printf("BEGIN:VEVENT\n");
		printf("UID:%s@scs.tufts.edu\n", generateUID($reminder_node));
		printf("METHOD:CANCEL\n");
		printf("STATUS:CANCELLED\n");
		printf("END:VEVENT\n");
	}
	
	$currentpath = '../data/reminders.xml';
	$lastknownpath = 'lastknown.xml';
	
	$current = simplexml_load_file($currentpath);
	
	// TODO fix this to use a URL instead of a file
	if ($current) {
		header('Content-Disposition: attachment;filename=reminders.vcal');

		
		// vcal header
		printf("BEGIN:VCALENDAR\n");
		printf("VERSION:2.0\n");
 
 /*
 		// diffing
		// steps (using UID generation to compare)
		//  - for each entry in lastknown not in current:
		//  	- using data in lastknown for uid, setup a cancellation
		//  - for each entry in current not in lastknown:
		// 		- using data in current, setup an event
		// 	- foreach entry in both current and lastknown:
		// 		- using data in current, setup an event
		//  - generalization: everything in current should be added
		//					  everything in lastknown and not in current should be cancelled
 
		// everything in lastknown and not in current should be cancelled
		if (file_exists($lastknownpath)) {
			$lastknown = simplexml_load_file($lastknownpath);
			
			foreach($lastknown->reminder as $lk_reminder) {
				// TODO is there a better approach than the naive one?
				$foundmatch = false;
				$lkUID = generateUID($lk_reminder);
				foreach($current->reminder as $c_reminder) {
					$cUID = generateUID($c_reminder);
					if (strcmp($lkUID, $cUID) == 0) {
						$foundmatch = true;
					}
				}
				
				if ($foundmatch == false) {
					printCancel($lk_reminder);
				}
			}

 
		}
*/

		// everything in current should be added
		foreach($current->reminder as $reminder) {
      if ($reminder["user"] == $_SESSION["username"] && $reminder["status"] == "okay")
        printEvent($reminder);
		}
	
		printf("END:VCALENDAR\n");
	/*
		$lastknownhandle = fopen ($lastknownpath, 'w');
		fwrite($lastknownhandle, $current->asXML());
		fclose($lastknownhandle);*/
	} else {
		exit('Failed to access reminder service.');
	}
?>